import type { INestApplication } from '@nestjs/common'
import type { OpenAPIObject } from '@nestjs/swagger'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'

export async function setupSwagger(app: INestApplication): Promise<OpenAPIObject> {
  const port = process.env.SERVE_PORT || 0
  const host = process.env.DATABASE_URL || ''

  const config = new DocumentBuilder()
    .setTitle('Docs')
    .setDescription(`The Json to click [this](http://${host}:${port}/api-docs/json)`)
    .setVersion('1.0')
    .build()

  // 确保库生成像 createUser 而不是 UserController_createUser 这样的操作名称
  const options = {
    operationIdFactory: (controllerKey: string, methodKey: string) => methodKey,
  }

  const document = SwaggerModule.createDocument(app, config, options)

  SwaggerModule.setup('api-docs', app, document, {
    jsonDocumentUrl: 'api-docs/json',
  })

  return document
}
